package cn.caidabao.gb.component.sip.server.storage;

import cn.caidabao.gb.bean.GBChannel;
import cn.caidabao.gb.bean.GBSipRegisterSession;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Component
public class SessionStorage {
    public static Map<String, GBSipRegisterSession> gbSessionStorage = new ConcurrentHashMap<>();

    public GBSipRegisterSession getSession(String user){
        return gbSessionStorage.get(user);
    }

    public Map<String, Set<String>> getAllDevices(String deviceId){
        LinkedHashMap<String,Set<String>> res = new LinkedHashMap<>();
        if (!StringUtils.hasLength(deviceId)){
            GBSipRegisterSession session = gbSessionStorage.get(deviceId);
            if (session != null){
                Set<String> channelIds = res.computeIfAbsent(deviceId, di -> new LinkedHashSet<>());
                ConcurrentMap<String, GBChannel> channelMap = session.getChannelMap();
                channelIds.addAll(channelMap.keySet());
            }
        }else {
            for (Map.Entry<String, GBSipRegisterSession> entry : gbSessionStorage.entrySet()) {
                String cDeviceId = entry.getKey();
                Set<String> channelIds = res.computeIfAbsent(cDeviceId, di -> new LinkedHashSet<>());
                ConcurrentMap<String, GBChannel> channelMap = entry.getValue().getChannelMap();
                channelIds.addAll(channelMap.keySet());
            }
        }
        return res;
    }
}
